package com.jzr.task.util;

import com.jzr.common.util.JsonUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

public class RestTemplateUtil {
    public static <T, A> T exchange(RestTemplate restTemplate, String url, HttpMethod method, ParameterizedTypeReference<T> responseBodyType, A requestBody) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));

        // 请求体
        headers.setContentType(mediaType);
        // 发送请求
        HttpEntity<A> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, responseBodyType);
        return resultEntity.getBody();
    }

    public static<T> T postJson(RestTemplate restTemplate, String url, Object requestObject, Class<T> responseType){
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> request = new HttpEntity<>(JsonUtil.toJson(requestObject),headers);

        return restTemplate.postForEntity(url,request,responseType).getBody();
    }
}
